package synchronization;

import java.util.Scanner;

class Worker extends Thread {
	
	private static Object room = new Object();

	@Override
	public void run() {
		System.out.println(this.getName() + ": Work began.");
		waitUntilWakedUp();
		System.out.println(this.getName() + ": Work finished.");
	}

	private void waitUntilWakedUp() {
		try {
			synchronized (room) {
				System.out.println(this.getName() + ": Falling into a sleep...");
				room.wait();
				System.out.println(this.getName() + ": Waked up.");
			}
		} catch (InterruptedException e) {
			System.out.println("Work interrupeted.");
		}
	}
	
	public static void wakeUpAnybody() {
		synchronized (room) {
			room.notify();
		}
	}
	
	public static void wakeUpAll() {
		synchronized (room) {
			room.notifyAll();
		}
	}
	
}

public class WaitAndNotifyExample {
	
	public static void main(String[] args) {
		Worker worker1 = new Worker();
		worker1.start();

		Worker worker2 = new Worker();
		worker2.start();
		
		Worker worker3 = new Worker();
		worker3.start();
		
		Scanner scanner = new Scanner(System.in);
		scanner.nextLine();
		//Worker.wakeUpAnybody();
		Worker.wakeUpAll();
	}
	
}
